import { getEntityMap } from '../base'
import type { Aircraft } from '../aircraft'
import type { Routing } from '../routing'
import type { FlightPlan } from './types'

export interface FlightPlanInfo extends FlightPlan {
  aircraftType: string
  depApt: string | null
  depFix: string | null
  arrApt: string | null
  arrFix: string | null
}

const fplInfos: Record<string, FlightPlanInfo> = {}

export function setupFlightPlanInfos(fplLst: FlightPlan[]) {
  const acs = getEntityMap<Aircraft>('Aircraft')
  const routings = getEntityMap<Routing>('Routing')

  function toInfo(fpl: FlightPlan): FlightPlanInfo {
    const routing = routings[fpl.routing]
    const depApt = routing.departureAirport ? routing.departureAirport : null
    const arrApt = routing.arrivalAirport ? routing.arrivalAirport : null
    const depFix = depApt ? routing.waypointList[0] : null
    const arrFix = arrApt ? routing.waypointList[routing.waypointList.length - 1] : null
    return {
      id: fpl.id,
      startTime: fpl.startTime,
      endTime: fpl.endTime,
      routing: fpl.routing,
      aircraft: fpl.aircraft,
      flightLevel: fpl.flightLevel,
      aircraftType: acs[fpl.aircraft].aircraftType,
      depApt,
      arrApt,
      depFix,
      arrFix
    }
  }
  for (const fpl of fplLst) {
    fplInfos[fpl.id] = toInfo(fpl)
  }
}

export function getFlightPlanInfoById(fid: string): FlightPlanInfo {
  return fplInfos[fid]
}

export function getFlightPlanInfoList(): FlightPlanInfo[] {
  return Object.values(fplInfos)
}
